/** software/vulnerabilities/:cve > Vulnerable software section */

import React, { useCallback, useMemo } from "react";

import { InjectedRouter } from "react-router";
import { Row } from "react-table";

import { IVulnerabilityResponse } from "services/entities/vulnerabilities";

import PATHS from "router/paths";
import { getPathWithQueryParams } from "utilities/url";

import Card from "components/Card";
import TableContainer from "components/TableContainer";
import TableCount from "components/TableContainer/TableCount";

import generateColumnConfigs from "./SwVulnSwTableConfig";

const baseClass = "software-vuln-software-versions";

interface IRowProps extends Row {
  original: {
    id?: number;
  };
}

interface ISoftwareVulnSoftwareVersions {
  vulnSoftware: IVulnerabilityResponse["software"];
  isPremiumTier: boolean;
  router: InjectedRouter;
  teamIdForApi?: number;
}

const SoftwareVulnSoftwareVersions = ({
  vulnSoftware,
  isPremiumTier,
  router,
  teamIdForApi,
}: ISoftwareVulnSoftwareVersions) => {
  const columnConfigs = useMemo(
    () => generateColumnConfigs(isPremiumTier, router, teamIdForApi),
    [isPremiumTier, router, teamIdForApi]
  );

  const handleRowSelect = (row: IRowProps) => {
    if (row.original.id) {
      const softwareVersionId = row.original.id;

      const softwareVersionDetailsPath = getPathWithQueryParams(
        PATHS.SOFTWARE_VERSION_DETAILS(softwareVersionId.toString()),
        {
          team_id: teamIdForApi,
        }
      );

      router.push(softwareVersionDetailsPath);
    }
  };

  const renderVulnerableSoftwareCount = useCallback(() => {
    return <TableCount name="items" count={vulnSoftware?.length} />;
  }, [vulnSoftware?.length]);

  const renderVulnerableSoftwareTable = () => {
    return (
      <TableContainer
        columnConfigs={columnConfigs}
        data={vulnSoftware}
        defaultSortHeader="hosts"
        defaultSortDirection="desc"
        isClientSidePagination
        isLoading={false} // not rendered otherwise
        emptyComponent={() => <></>}
        showMarkAllPages={false}
        isAllPagesSelected={false}
        disableMultiRowSelect
        onSelectSingleRow={handleRowSelect}
        renderCount={renderVulnerableSoftwareCount}
      />
    );
  };
  return (
    <Card borderRadiusSize="xxlarge" className={`${baseClass}`}>
      <h2>Vulnerable software</h2>
      {renderVulnerableSoftwareTable()}
    </Card>
  );
};

export default SoftwareVulnSoftwareVersions;
